// #include <strings.h>
#include <string>
#include <string.h>    // memset()、bzero()
#include <arpa/inet.h> //inet_addr()

#include "./InetAddress.h"

InetAddress::InetAddress(const uint16_t port, const std::string ip)
{
    // ::memset(&addr_, 0, sizeof(addr_));
    ::bzero(&(this->addr_), sizeof(this->addr_));

    this->addr_.sin_family = AF_INET;
    this->addr_.sin_addr.s_addr = ::inet_addr(ip.c_str());
    this->addr_.sin_port = ::htons(port); // 本地字节序->网络字节序
}

InetAddress::InetAddress(const sockaddr_in &addr) : addr_(addr)
{
}

const sockaddr_in *InetAddress::getAddr() const
{
    return &this->addr_;
}

void InetAddress::setAddr(const sockaddr_in &addr)
{
    this->addr_ = addr;
}

std::string InetAddress::toIp() const
{
    char buf[64]{0};

    ::inet_ntop(AF_INET, &(this->addr_).sin_addr, buf, sizeof(buf));
    // 注意：构造函数转成网络字节序，需要转换回本地字节序

    return buf;
}

uint16_t InetAddress::toPort() const
{
    return ::ntohs(this->addr_.sin_port);
}

std::string InetAddress::toIpPort() const
{
    // ip:port
    char buf[64]{0};

    ::inet_ntop(AF_INET, &(this->addr_).sin_addr, buf, sizeof(buf));
    size_t end = ::strlen(buf);
    uint16_t port = ::ntohs(this->addr_.sin_port);
    sprintf(buf + end, ":%u", port);
    // buf是0地址，从ip长度end后开始拼接

    return buf;
}

// #include <iostream>
// int main()
// {
//     InetAddress addr(8080);
//     std::cout << addr.toIpPort() << std::endl;

//     return 0;
// }